<template>
    <div>
        <div class="page-title">
            <text>患者设备绑定</text>
        </div>
        <!-- 患者卡片区域 -->
        <div class="patients-section">
            <div class="section-header">
                <div style="font-size: 1.25rem; font-weight: normal">当前监测患者</div>
                <div style="display: flex; gap: 0.75rem">
                    <a-button class="btn btn-outline" @click="loadPatients">
                        <text>刷新患者</text>
                    </a-button>
                    <button class="btn btn-outline" @click="loadAvailableDevices">
                        <text>刷新设备</text>
                    </button>
                    <button class="btn btn-primary" @click="showModal = true">
                        <text>添加新患者</text>
                    </button>
                </div>
            </div>
            <div class="patients-grid">
                <!-- 根据传入参数，更新esp32设备数据，每个病人卡片显示不同数据 -->
                <!--  :class="getCardBorderClass(patient.pressure)"  @click="showMonitor(patient.deviceId)"> -->
                <div class="patient-card" v-for="(patient, index) in patients" :key="index"
                    :class="getCardBorderClass(patient.pressure)"
                    @click="patient.deviceId ? showMonitor(patient) : null">
                    <div class="card-header">
                        <div class="patient-info">
                            <div class="patient-name">{{ patient.name }}</div>
                            <div class="patient-id">住院号: {{ patient.hospitalId }}</div>
                        </div>
                        <div class="device-info">
                            <div class="device-row" v-if="patient.deviceId && patient.deviceId !== ''">
                                <div class="device-id">{{ "ESP32-" + patient.deviceId }}</div>
                                <button class="btn btn-outline btn-sm"
                                    @click.stop="unbindDevice(patient.id, patient.deviceId)"
                                    style="width: 80px; height: 25px">
                                    解 绑
                                </button>
                            </div>
                            <div class="device-id" v-else style="color: #64748b">
                                未绑定设备
                            </div>
                            <!--              <div class="device-status" v-if="patient.deviceStatus" :class="'status-' + patient.deviceStatus">
                {{ patient.deviceStatus }}
              </div> -->
                        </div>
                    </div>
                    <div class="card-content">
                        <div>
                            <div class="pressure-value">{{ patient.pressure }} kPa</div>
                            <div class="pressure-label">膀胱压力</div>
                        </div>
                        <div class="pressure-status" :class="getStatusClass(patient.status)">
                            {{ patient.statusText }}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 添加患者模态框 - 新增点击空白处关闭功能 -->
        <div class="modal-overlay" v-if="showModal" @click="closeModalByOverlay">
            <div class="modal-content" @click.stop>
                <div class="modal-header">
                    <div class="modal-title">患者设备绑定</div>
                    <button class="close-btn" @click="showModal = false">
                        <text class="iconfont icon-times">×</text>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-row">
                        <div class="form-group">
                            <text class="form-label">患者姓名</text>
                            <a-input type="text" class="form-control" placeholder="输入患者姓名" v-model="newPatient.name" />
                        </div>
                        <div class="form-group">
                            <text class="form-label">住院号</text>
                            <a-input type="text" class="form-control" placeholder="输入住院号"
                                v-model="newPatient.hospitalId" />
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <text class="form-label">性别</text>
                            <a-select style="width: 90%" v-model:value="newPatient.gender" placeholder="选择性别"
                                @change="(value) => (newPatient.gender = value)" allowClear>
                                <a-select-option value="male">男</a-select-option>
                                <a-select-option value="female">女</a-select-option>
                            </a-select>
                        </div>
                        <div class="form-group">
                            <text class="form-label">年龄</text>
                            <a-input type="number" placeholder="输入年龄" v-model="newPatient.age" />
                        </div>
                        <div class="form-group">
                            <text class="form-label">手机号</text>
                            <!-- <a-input type="number" placeholder="输入手机号" v-model="newPatient.phone" maxlength="11"
                                pattern="[0-9]*" inputmode="numeric" /> -->
                            <a-input type="tel" placeholder="输入手机号" v-model="newPatient.phone" :maxlength="11" :rules="[
                                { required: true, message: '请输入手机号', trigger: 'blur' },
                                {
                                    pattern: /^1[3-9]\d{9}$/,
                                    message: '请输入正确的手机号格式',
                                    trigger: 'blur',
                                },
                            ]" />
                        </div>
                    </div>
                    <div class="form-group">
                        <text class="form-label">选择设备</text>
                        <!-- <picker class="select-control" :range="availableDevices" range-key="device_id"
                            @change="onDeviceChange" :disabled="availableDevices.length === 0">
                            <div class="picker" :class="{ disabled: availableDevices.length === 0 }">
                                {{
                                    selectedDevice?.device_id ||
                                    (availableDevices.length === 0
                                        ? "暂无可绑定设备"
                                        : "选择要绑定的ESP32设备")
                                }}
                            </div>
                        </picker> -->
                        <!-- <a-select 
                            style="width: 100%" 
                            v-model:value="selectedDevice?.device_id"
                            placeholder="选择要绑定的ESP32设备"
                            :disabled="availableDevices.length === 0"
                            @change="onDeviceChange"
                        >
                            <a-select-option 
                                v-for="device in availableDevices" 
                                :key="device.id || device.device_id"
                                :value="device.device_id"
                            >
                                {{ device.device_id }} ({{ device.machine_id }})
                            </a-select-option>
                        </a-select> -->
                        <a-select style="width: 100%" v-model:value="selectedDeviceId" @change="onDeviceChange"
                            placeholder="选择要绑定的ESP32设备" :disabled="availableDevices.length === 0" allowClear>
                            <a-select-option v-for="device in availableDevices" :key="device.id || device.device_id"
                                :value="device.device_id">
                                {{ device.device_id }} ({{ device.machine_id }})
                            </a-select-option>
                        </a-select>
                        <text v-if="availableDevices.length === 0" class="form-help">所有设备已被绑定，请先解除其他患者的设备绑定</text>
                    </div>
                    <div class="form-group">
                        <text class="form-label">可用设备列表</text>
                        <div class="device-list">
                            <div class="device-item" v-for="(device, index) in availableDevices" :key="index"
                                :class="{ active: device.id === selectedDevice?.id }"
                                @click="selectDevice(device.device_id)">
                                <div class="device-info">
                                    <div class="device-id-label">{{ device.device_id }}</div>
                                    <div class="device-details">
                                        <text class="device-mac">机器ID: {{ device.machine_id }}</text>
                                        <text class="device-status" :class="'status-' + device.status">{{ device.status
                                        }}</text>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button class="btn btn-cancel" @click="resetModal">清除</button>
                    <button class="btn btn-primary" @click="bindDevice" :disabled="availableDevices.length === 0">
                        确认绑定
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
// import { patientsAPI, devicesAPI, sensorAPI } from '@/api/index.js'

import { message } from "ant-design-vue";
import { useRouter } from "vue-router";
const router = useRouter();
import {
    getPatients,
    getAllPatientDeviceBindings,
    addPatient,
    bindPatientDevice,
    deletePatient,
    unbindPatientDevice,
} from "@/api/patientsAPI.js";
import { getDevices, updateDevice } from "@/api/devicesAPI.js";
import { getSensorData } from "@/api/sensorAPI.js";
const showModal = ref(false);
const patients = ref([]);
const availableDevices = ref([]);
const loading = ref(false);
const newPatient = ref({
    name: "",
    gender: "",
    age: "",
    phone: "",
    hospitalId: "",
    id: null,
});
const selectedDevice = ref(null);
const selectedDeviceId = ref()
// 获取患者列表
const loadPatients = async () => {
    loading.value = true;
    try {
        const res = await getPatients({ page: 1, size: 100 });
        // console.log(res);

        let patientData =
            res?.data?.data?.list ||
            res?.data?.list ||
            res?.patients ||
            res?.data ||
            res;

        // console.log(
        //     "patientData:",
        //     patientData,
        //     "type:",
        //     typeof patientData,
        //     "isArray:",
        //     Array.isArray(patientData)
        // );
        if (!Array.isArray(patientData)) {
            // 如果 patientData 不是数组，尝试取它的 list 属性
            if (Array.isArray(patientData?.list)) {
                patientData = patientData.list;
            } else {
                patientData = [];
            }
        }

        // 获取最新的传感器数据（每个患者的最新压力数据）
        let latestSensorData = {};
        try {
            // 获取所有传感器数据，按患者ID分组，取最新的
            const sensorRes = await getSensorData({ page: 1, size: 100 });
            // console.log("传感器数据响应:", sensorRes);

            // 适配后端返回的数据结构
            let sensorDataList = sensorRes.data.devices;

            // console.log("处理后的传感器数据列表:", sensorDataList);

            // 按患者ID分组，获取每个患者的最新数据
            sensorDataList.forEach((sensor) => {
                // console.log("处理传感器数据:", sensor);
                // 检查可能的患者ID字段名
                const patientId =
                    sensor.patient_id || sensor.patientId || sensor.patient;
                if (patientId) {
                    if (
                        !latestSensorData[patientId] ||
                        new Date(sensor.timestamp) >
                        new Date(latestSensorData[patientId].timestamp)
                    ) {
                        latestSensorData[patientId] = sensor;
                    }
                } else {
                    // console.log("传感器数据缺少患者ID:", sensor);
                }
            });

            // console.log("按患者ID分组的最新传感器数据:", latestSensorData);
        } catch (sensorError) {
            console.log("获取传感器数据失败:", sensorError);
        }

        // 获取患者设备绑定信息
        let patientBindings = {};
        try {
            // 尝试调用真实的API
            const bindingsRes = await getAllPatientDeviceBindings();
            // console.log("绑定信息响应:", bindingsRes);

            // 安全地获取数据
            if (bindingsRes && bindingsRes.data) {
                patientBindings = bindingsRes.data;
            } else if (bindingsRes && typeof bindingsRes === "object") {
                // 如果响应直接是对象
                patientBindings = bindingsRes;
            } else {
                console.log("绑定信息响应格式异常:", bindingsRes);
                patientBindings = {};
            }
        } catch (bindingError) {
            console.log("获取绑定信息失败:", bindingError);
            // 使用空对象作为默认值
            patientBindings = {};
        }
        // console.log("绑定信息响应:", patientBindings);

        patients.value = patientData.map((p) => {
            // 获取该患者的最新传感器数据
            // 使用 patient_id（住院号）作为关联字段，因为传感器数据可能使用住院号关联
            const patientId = p.patient_id || p.id;
            const sensorData = latestSensorData[patientId];
            const binding = patientBindings[patientId];

            let pressure = 0;
            let deviceId = "";
            let deviceStatus = "disconnected";

            if (sensorData) {
                pressure = sensorData.pressure || 1234;
            }
            // 优先从传感器数据获取设备ID
            if (sensorData && sensorData.device_id) {
                deviceId = sensorData.machine_code;
                deviceStatus = "connected";
            } else if (binding && binding.status === "active") {
                // 如果没有传感器数据，则从绑定信息获取
                deviceId = binding.device_id;
                deviceStatus = "connected";
            }

            // 根据压力值自动判断状态
            let status = "normal";
            let statusText = "正常";

            if (pressure > 15 && pressure < 20) {
                status = "warning";
                statusText = "轻度压力增高";
            } else if (pressure >= 20) {
                status = "danger";
                statusText = "压力过高";
            }

            return {
                ...p,
                name: p.name,
                hospitalId: p.patient_id, // 使用数据库中的 patient_id 字段
                deviceId: deviceId,
                pressure: pressure,
                status: status,
                statusText: statusText,
                deviceStatus: deviceStatus,
            };
        });
    } catch (e) {
        // console.log("使用测试数据:", e);
    }
    loading.value = false;
};

// 获取可用设备列表
const loadAvailableDevices = async () => {
    loading.value = true;
    try {
        // 获取所有设备
        const res = await getDevices();
        // console.log("获取所有设备响应:", res);
        let deviceData = res.data;

        // 获取所有患者的设备绑定信息
        const patientsRes = await getAllPatientDeviceBindings({
            page: 1,
            size: 1000,
        });
        // console.log("获取所有患者绑定信息响应:", patientsRes);
        const patientsList = patientsRes.data;

        // 收集所有已绑定的设备ID
        const boundDeviceIds = new Set();
        for (const patient of patientsList) {
            if (patient.device_id) {
                boundDeviceIds.add(patient.device_id);
            }
        }

        // 过滤掉已绑定的设备
        const availableDeviceData = deviceData.filter(
            (device) => !boundDeviceIds.has(device.device_id)
        );

        availableDevices.value = availableDeviceData.map((d) => ({
            ...d,
            id: d.id,
            device_id: d.device_id, // 保持原始字段
            machine_id: d.machine_id, // 机器ID
            status: d.status, // 设备状态
        }));

        // console.log("可用设备数量:", availableDevices.value.length);
        // console.log("已绑定设备ID:", Array.from(boundDeviceIds));
        // console.log(
        //     "可用设备列表:",
        //     availableDevices.value.map((d) => d.device_id)
        // );
    } catch (e) {
        console.error("获取设备失败:", e);
        // 如果API调用失败，使用测试数据
    }
    loading.value = false;
};

// 绑定设备
const bindDevice = async () => {
    if (
        !newPatient.value.name ||
        !newPatient.value.hospitalId ||
        !selectedDevice.value
    ) {
        // uni.showToast({ title: "请完善患者信息并选择设备", icon: "none" });
        message.error("请完善患者信息并选择设备!");
        return;
    }
    // 手机号校验：必须为11位数字
    if (!/^\d{11}$/.test(newPatient.value.phone)) {
        // uni.showToast({ title: "请输入11位手机号", icon: "none" });
        message.error("请输入11位手机号!");
        return;
    }

    try {
        // 先添加患者（如有必要）
        let patientId = newPatient.value.id; // 页面ref的患者ID
        let isNewPatient = false;

        // 如果是新患者，先添加患者
        if (!patientId) {
            isNewPatient = true;
            const addRes = await addPatient({
                name: newPatient.value.name,
                gender: newPatient.value.gender,
                age: newPatient.value.age,
                phone: newPatient.value.phone,
                patient_id: newPatient.value.hospitalId, // 这里用后端字段名
            });
            patientId =
                addRes.data?.data?.patient_id ||
                addRes.data?.patient_id ||
                addRes.patient_id;
        }
        // 绑定设备
        await bindPatientDevice({
            patient_id: patientId,
            device_id: selectedDevice.value.device_id, // 使用 device_id 字段
        });

        // 绑定成功后，更新设备状态为 connected
        try {
            await updateDevice(selectedDevice.value.device_id, {
                status: "connected",
            });
            console.log(
                "设备状态已更新为 connected:",
                selectedDevice.value.device_id
            );
        } catch (updateError) {
            console.error("创建绑定失败:", updateError);
            throw new Error("设备绑定失败");
        }

        // uni.showToast({ title: "设备绑定成功", icon: "success" });
        message.success("设备绑定成功!");
        showModal.value = false;
        resetModal();
        // 刷新数据 - 先刷新患者列表，再刷新设备列表
        await loadPatients();
        await loadAvailableDevices();
    } catch (e) {
        console.error("绑定失败:", e);

        // 如果是新患者且绑定失败，可以考虑删除刚创建的患者
        // 注意：这里需要后端提供删除患者的API
        if (isNewPatient && patientId) {
            try {
                // 如果后端有删除患者的API，可以在这里调用
                await deletePatient(patientId);
                console.log("患者已创建但设备绑定失败，建议手动清理数据");
            } catch (deleteError) {
                console.error("清理患者数据失败:", deleteError);
            }
        }
        // uni.showToast({
        //     title: "绑定失败，请重试",
        //     icon: "none",
        //     duration: 2000,
        // });
        message.error("绑定失败，请重试!");
    }
};

// 关闭模态框
const closeModalByOverlay = () => {
    showModal.value = false;
    resetModal();
};

// 清空表单
const resetModal = () => {
    newPatient.value = {
        name: "",
        gender: "",
        age: "",
        phone: "",
        hospitalId: "",
        id: null,
    };
    selectedDevice.value = null;
};

// 选择设备
const selectDevice = (device) => {
    selectedDeviceId.value = device;
};

// picker选择设备
const onDeviceChange = () => {
    selectedDevice.value = availableDevices.value.find(item => {
        return item.device_id === selectedDeviceId.value
    })


    // selectedDevice.value = availableDevices.value[e.detail.value];
};

// 跳转到监控页面
const showMonitor = (item) => {
    if (!item.hospitalId) {
        // uni.showToast({ title: "该患者未绑定设备", icon: "none" });
        message.error("该患者未绑定设备!");
        return;
    }
    // console.log("住院号：", item.hospitalId);
    // uni.navigateTo({
    //     url: "/pages/pressureMonitor/pressureMonitor?deviceId=" + item.deviceId,
    // });
    router.push({
        path: "/pressureMonitor",
        query: {
            deviceId: item.deviceId,
        },
    });
};

// 解除设备绑定
const unbindDevice = async (patientId, deviceId) => {
    try {
        // 解除患者设备绑定
        await unbindPatientDevice(patientId);

        // 更新设备状态为 disconnected
        await updateDevice(deviceId, {
            status: "disconnected",
        });

        // uni.showToast({ title: "设备解绑成功", icon: "success" });
        message.success("设备解绑成功!");

        // 刷新数据
        await loadPatients();
        await loadAvailableDevices();
    } catch (e) {
        // console.error("解绑失败:", e);
        message.error("解绑失败，请重试!");
    }
};

// 状态样式
const getStatusClass = (status) => {
    switch (status) {
        case "normal":
            return "status-normal";
        case "warning":
            return "status-warning";
        case "danger":
            return "status-danger";
        default:
            return "status-normal";
    }
};

// 获取卡片边框样式
const getCardBorderClass = (pressure) => {
    if (pressure > 15 && pressure < 20) {
        return "warning";
    } else if (pressure >= 20) {
        return "danger";
    }
    return "normal";
};

// 页面加载时获取数据
onMounted(() => {
    loadPatients();
    loadAvailableDevices();
});
</script>

<style scoped lang="scss">
/* 变量定义 */
$primary: #2563eb;
$primary-dark: #1d4ed8;
$secondary: #64748b;
$success: #10b981;
$warning: #f59e0b;
$danger: #ef4444;
$light-bg: #f8fafc;
$card-bg: #ffffff;
$border: #e2e8f0;
$text: #1e293b;
$text-light: #64748b;

.page-title {
    font-size: 1.5rem;
    font-weight: 600;
    margin-bottom: 1.5625rem;
    display: flex;
    align-items: center;
}

.patients-section {
    margin-bottom: 1.875rem;

    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.25rem;
    }

    .patients-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(18.75rem, 1fr));
        gap: 1.25rem;
    }

    .patient-card {
        background: #fff;
        border-radius: 0.75rem;
        box-shadow: 0 0.25rem 0.75rem rgba(0, 0, 0, 0.05);
        padding: 1.25rem;
        transition: transform 0.3s, box-shadow 0.3s;
        border-left: 0.25rem solid #10b981;
        cursor: pointer;

        &.normal {
            border-left-color: #10b981;
        }

        &.warning {
            border-left-color: #f59e0b;
        }

        &.danger {
            border-left-color: #ef4444;
        }

        &:hover {
            transform: translateY(-0.3125rem);
            box-shadow: 0 0.5rem 1.25rem rgba(0, 0, 0, 0.1);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 0.9375rem;
            padding-bottom: 0.9375rem;
            border-bottom: 1px solid #e2e8f0;

            .patient-info {
                display: flex;
                flex-direction: column;
                gap: 0.25rem;
            }

            .patient-name {
                font-size: 1.125rem;
                font-weight: 600;
                color: #1e293b;
            }

            .patient-id {
                font-size: 0.875rem;
                color: #64748b;
            }

            .device-info {
                display: flex;
                flex-direction: column;
                align-items: flex-end;
                gap: 0.5rem;
            }

            .device-row {
                display: flex;
                flex-direction: column;
                align-items: flex-end;
                gap: 0.5rem;
            }

            .device-id {
                background: rgba(37, 99, 235, 0.1);
                color: #2563eb;
                padding: 0.25rem 0.625rem;
                border-radius: 1.25rem;
                font-size: 0.8125rem;
                font-weight: 500;
            }
        }

        .card-content {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .pressure-value {
                font-size: 1.75rem;
                font-weight: 700;
                color: #2563eb;
            }

            .pressure-label {
                font-size: 0.875rem;
                color: #64748b;
                margin-top: 0.25rem;
            }

            .pressure-status {
                padding: 0.375rem 0.75rem;
                border-radius: 1.25rem;
                font-size: 0.875rem;
                font-weight: 500;
            }

            .status-normal {
                background: rgba(16, 185, 129, 0.1);
                color: #10b981;
            }

            .status-warning {
                background: rgba(245, 158, 11, 0.1);
                color: #f59e0b;
            }

            .status-danger {
                background: rgba(239, 68, 68, 0.1);
                color: #ef4444;
            }

            .status-connected {
                background: rgba(16, 185, 129, 0.1);
                color: #10b981;
            }

            .status-disconnected {
                background: rgba(107, 114, 128, 0.1);
                color: #6b7280;
            }

            .status-busy {
                background: rgba(245, 158, 11, 0.1);
                color: #f59e0b;
            }

            .status-error {
                background: rgba(239, 68, 68, 0.1);
                color: #ef4444;
            }
        }
    }
}

/* 按钮样式 */
.btn {
    padding: 0.6rem 1.25rem;
    border-radius: 0.5rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;

    .iconfont {
        margin-right: 0.5rem;
    }

    &.btn-primary {
        background: $primary;
        color: white;
        padding: 0.12rem 0.8rem;
    }

    &.btn-primary:hover {
        background: $primary-dark;
    }

    &.btn-outline {
        background: transparent;
        border: 1px solid $primary;
        color: $primary;
        padding: 0.12rem 0.8rem;
    }

    &.btn-outline:hover {
        background: rgba(37, 99, 235, 0.05);
    }

    &.btn-cancel {
        background: #f1f5f9;
        color: $text;
    }

    &.btn-cancel:hover {
        background: #e2e8f0;
    }

    &.btn-sm {
        padding: 0rem 0.5rem;
        font-size: 0.8rem;
        border-radius: 0.25rem;
        writing-mode: horizontal-tb;
        text-orientation: mixed;
    }
}

/* 模态框样式 - 优化关闭交互 */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 100;
    // backdrop-filter: blur(2px); /* 毛玻璃效果 */

    .modal-content {
        background: white;
        border-radius: 0.75rem;
        width: 37.5rem;
        max-width: 90%;
        box-shadow: 0 0.625rem 1.875rem rgba(0, 0, 0, 0.2);
        overflow: hidden;
        animation: modalIn 0.3s ease-out;
        /* 添加打开动画 */

        .modal-header {
            padding: 1.25rem 1.5625rem;
            background: $primary;
            color: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;

            /* 新增：让关闭按钮绝对定位到右上角 */
            .modal-title {
                font-size: 1.25rem;
                font-weight: 600;
            }

            .close-btn {
                background: none;
                border: none;
                color: white;
                font-size: 1.5rem;
                cursor: pointer;
                width: 2.25rem;
                height: 2.25rem;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 50%;
                transition: all 0.2s;
                position: absolute;
                right: 1.25rem;
                top: 1.25rem;
                padding-bottom: 10rpx;

                /* 让按钮悬浮在右上角 */
                &:hover {
                    background: rgba(255, 255, 255, 0.2);
                }
            }
        }

        .modal-body {
            padding: 1.5625rem;

            .form-group {
                margin-bottom: 1.25rem;

                .form-label {
                    display: block;
                    margin-bottom: 0.5rem;
                    font-weight: 500;
                    color: $text;
                }

                .form-control {
                    width: 90%;
                    padding: 0.75rem 0.9375rem;
                    border: 1px solid $border;
                    border-radius: 0.5rem;
                    font-size: 1rem;
                    transition: all 0.3s;
                }

                .form-control:focus {
                    outline: none;
                    border-color: $primary;
                    box-shadow: 0 0 0 0.1875rem rgba(37, 99, 235, 0.1);
                }

                .form-help {
                    font-size: 0.875rem;
                    color: $text-light;
                    margin-top: 0.5rem;
                    display: block;
                }

                .select-control {
                    width: 95%;
                    padding: 0.75rem 0.9375rem;
                    border: 1px solid $border;
                    border-radius: 0.5rem;
                    font-size: 1rem;
                    background: white;
                    appearance: none;
                    background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' divBox='0 0 24 24' fill='none' stroke='%232563eb' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
                    background-repeat: no-repeat;
                    background-position: right 0.9375rem center;
                    background-size: 1rem;
                }

                .select-control:focus {
                    outline: none;
                    border-color: $primary;
                    box-shadow: 0 0 0 0.1875rem rgba(37, 99, 235, 0.1);
                }

                .picker {
                    &.disabled {
                        color: $text-light;
                        background-color: #f1f5f9;
                        cursor: not-allowed;
                    }
                }
            }

            .form-row {
                display: flex;
                gap: 1.25rem;

                .form-group {
                    flex: 1;
                }
            }

            .device-list {
                border: 1px solid $border;
                border-radius: 0.5rem;
                max-height: 12.5rem;
                overflow-y: auto;
                margin-top: 0.9375rem;

                .device-item {
                    padding: 0.75rem 0.9375rem;
                    border-bottom: 1px solid $border;
                    cursor: pointer;
                    transition: all 0.2s;

                    &:last-child {
                        border-bottom: none;
                    }

                    &:hover {
                        background: rgba(37, 99, 235, 0.05);
                    }

                    &.active {
                        background: rgba(37, 99, 235, 0.1);
                        border-left: 0.1875rem solid $primary;
                    }

                    .device-info {
                        display: flex;
                        align-items: center;
                        gap: 0.625rem;
                    }

                    .device-id-label {
                        font-weight: 500;
                        font-size: 1rem;
                    }

                    .device-details {
                        display: flex;
                        gap: 0.3125rem;
                        font-size: 0.8125rem;
                        color: $text-light;
                    }

                    .device-status {
                        padding: 0.1875rem 0.5rem;
                        border-radius: 0.375rem;
                        font-weight: 500;
                    }

                    .status-normal {
                        background: rgba(16, 185, 129, 0.1);
                        color: #10b981;
                    }

                    .status-warning {
                        background: rgba(245, 158, 11, 0.1);
                        color: #f59e0b;
                    }

                    .status-danger {
                        background: rgba(239, 68, 68, 0.1);
                        color: #ef4444;
                    }

                    .status-connected {
                        background: rgba(16, 185, 129, 0.1);
                        color: #10b981;
                    }

                    .status-disconnected {
                        background: rgba(107, 114, 128, 0.1);
                        color: #6b7280;
                    }

                    .status-busy {
                        background: rgba(245, 158, 11, 0.1);
                        color: #f59e0b;
                    }

                    .status-error {
                        background: rgba(239, 68, 68, 0.1);
                        color: #ef4444;
                    }
                }
            }
        }

        .modal-footer {
            padding: 1.25rem 1.5625rem;
            background: #f9fafb;
            display: flex;
            justify-content: flex-end;
            gap: 0.75rem;
        }
    }
}

/* 模态框动画 */
@keyframes modalIn {
    from {
        opacity: 0;
        transform: translateY(-20px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>
